import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../main.dart';
import '../pages/home_page.dart';
import '../pages/order_detail_page.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> {
  final Map<String, RefreshController> _refreshControllers = {
    'pending_accept': RefreshController(),
    'serving': RefreshController(),
    'pending': RefreshController(),
    'completed': RefreshController(),
    'cancelled': RefreshController(),
  };

  final Map<String, List<OrderItem>> _orderLists = {
    'pending_accept': [],
    'serving': [],
    'pending': [],
    'completed': [],
    'cancelled': [],
  };

  @override
  void dispose() {
    _refreshControllers.values.forEach((controller) => controller.dispose());
    super.dispose();
  }

  Future<void> _onRefresh(String type) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));
    
    setState(() {
      _orderLists[type] = _getOrders(type);
    });
    
    _refreshControllers[type]!.refreshCompleted();
  }

  Future<void> _onLoading(String type) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 2));
    
    // 模拟加载更多数据
    final moreOrders = _getOrders(type);
    if (moreOrders.isNotEmpty) {
      setState(() {
        _orderLists[type]!.addAll(moreOrders);
      });
      _refreshControllers[type]!.loadComplete();
    } else {
      _refreshControllers[type]!.loadNoData();
    }
  }

  @override
  void initState() {
    super.initState();
    // 初始化每个标签页的订单列表数据
    _orderLists['pending_accept'] = List.generate(10, (i) => OrderItem(
      title: '大件搬运服务 ${i + 1}',
      description: '北京市朝阳区 → 海淀区',
      time: '2024-01-${21 - i} 10:30',
      amount: 399 + i * 10,
      status: 'pending_accept',
      actions: ['取消订单', '修改订单'],
    ));

    _orderLists['serving'] = List.generate(10, (i) => OrderItem(
      title: '大件搬运服务 ${i + 1}',
      description: '北京市朝阳区 → 海淀区',
      time: '2024-01-${20 - i} 14:30',
      amount: 299 + i * 10,
      status: 'serving',
      actions: ['取消订单'],
    ));

    _orderLists['pending'] = List.generate(10, (i) => OrderItem(
      title: '家具拆装服务 ${i + 1}',
      description: '北京市西城区望京南路10号',
      time: '2024-01-${19 - i} 16:20',
      amount: 199 + i * 10,
      status: 'pending',
      actions: ['立即支付'],
    ));

    _orderLists['completed'] = List.generate(10, (i) => OrderItem(
      title: '小件搬运服务 ${i + 1}',
      description: '北京市海淀区中关村',
      time: '2024-01-${18 - i} 09:30',
      amount: 149 + i * 10,
      status: 'completed',
      actions: ['再次下单'],
    ));

    _orderLists['cancelled'] = List.generate(10, (i) => OrderItem(
      title: '小件搬运服务 ${i + 1}',
      description: '北京市东城区东直门',
      time: '2024-01-${17 - i} 11:20',
      amount: 99 + i * 10,
      status: 'cancelled',
      actions: ['重新下单'],
    ));
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        backgroundColor: const Color(0xFFF7F7F7),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          flexibleSpace: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TabBar(
                isScrollable: false,
                labelColor: Theme.of(context).colorScheme.primary,
                unselectedLabelColor: Colors.grey,
                indicatorColor: Theme.of(context).colorScheme.primary,
                indicatorSize: TabBarIndicatorSize.label,
                labelPadding: const EdgeInsets.symmetric(horizontal: 8),
                labelStyle: const TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 15,
                ),
                indicatorWeight: 2,
                dividerColor: Colors.transparent,
                tabs: const [
                  Tab(text: '服务中'),
                  Tab(text: '待结算'),
                  Tab(text: '已完成'),
                  Tab(text: '已取消'),
                ],
              ),
            ],
          ),
          toolbarHeight: 56,
        ),
        body: TabBarView(
          children: [
            _buildOrderList('serving'),
            _buildOrderList('pending'),
            _buildOrderList('completed'),
            _buildOrderList('cancelled'),
          ],
        ),
      ),
    );
  }

  Widget _buildOrderList(String type) {
    if (_orderLists[type]!.isEmpty) {
      return SmartRefresher(
        controller: _refreshControllers[type]!,
        onRefresh: () => _onRefresh(type),
        header: const ClassicHeader(
          idleText: "下拉刷新",
          releaseText: "松开刷新",
          refreshingText: "正在刷新...",
          completeText: "刷新完成",
          failedText: "刷新失败",
          height: 38,
          refreshingIcon: SizedBox(
            width: 15,
            height: 15,
            child: CircularProgressIndicator(
              strokeWidth: 2,
            ),
          ),
          textStyle: TextStyle(
            fontSize: 13,
            color: Color(0xFF666666),
          ),
        ),
        child: _buildEmptyState(type),
      );
    }

    return SmartRefresher(
      controller: _refreshControllers[type]!,
      onRefresh: () => _onRefresh(type),
      onLoading: () => _onLoading(type),
      enablePullUp: true,
      header: const ClassicHeader(
        idleText: "下拉刷新",
        releaseText: "松开刷新",
        refreshingText: "正在刷新...",
        completeText: "刷新完成",
        failedText: "刷新失败",
        height: 38,
        refreshingIcon: SizedBox(
          width: 15,
          height: 15,
          child: CircularProgressIndicator(
            strokeWidth: 2,
          ),
        ),
        textStyle: TextStyle(
          fontSize: 13,
          color: Color(0xFF666666),
        ),
      ),
      footer: const ClassicFooter(
        idleText: "上拉加载更多",
        loadingText: "正在加载...",
        noDataText: "没有更多数据了",
        failedText: "加载失败，点击重试",
        canLoadingText: "松手加载更多",
        height: 38,
        loadingIcon: SizedBox(
          width: 15,
          height: 15,
          child: CircularProgressIndicator(
            strokeWidth: 2,
          ),
        ),
        textStyle: TextStyle(
          fontSize: 13,
          color: Color(0xFF666666),
        ),
      ),
      child: ListView.builder(
        padding: const EdgeInsets.all(15),
        itemCount: _orderLists[type]!.length,
        itemBuilder: (context, index) {
          return _buildOrderItem(_orderLists[type]![index]);
        },
      ),
    );
  }

  Widget _buildEmptyState(String type) {
    return Builder(
      builder: (context) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/empty_order.png',
              width: 120,
              height: 120,
              errorBuilder: (context, error, stackTrace) {
                return Icon(
                  _getEmptyIcon(type),
                  size: 80,
                  color: Colors.grey[300],
                );
              },
            ),
            const SizedBox(height: 16),
            Text(
              _getEmptyText(type),
              style: TextStyle(
                fontSize: 15,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 20),
            OutlinedButton(
              onPressed: () => _goToPlaceOrder(context),
              style: OutlinedButton.styleFrom(
                foregroundColor: Theme.of(context).colorScheme.primary,
                side: BorderSide(
                  color: Theme.of(context).colorScheme.primary,
                ),
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('去下单'),
            ),
          ],
        ),
      ),
    );
  }

  void _goToPlaceOrder(BuildContext context) {
    Navigator.of(context).pushAndRemoveUntil(
      PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) => const MainPage(initialIndex: 0),
        transitionDuration: Duration.zero,
        reverseTransitionDuration: Duration.zero,
      ),
      (route) => false, // 清除所有路由历史
    );
  }

  IconData _getEmptyIcon(String type) {
    switch (type) {
      case 'pending_accept':
        return Icons.access_time_outlined;
      case 'serving':
        return Icons.local_shipping_outlined;
      case 'pending':
        return Icons.payment_outlined;
      case 'completed':
        return Icons.check_circle_outline;
      case 'cancelled':
        return Icons.cancel_outlined;
      default:
        return Icons.inbox_outlined;
    }
  }

  String _getEmptyText(String type) {
    switch (type) {
      case 'pending_accept':
        return '暂无待接单的订单';
      case 'serving':
        return '暂无服务中的订单';
      case 'pending':
        return '暂无待结算的订单';
      case 'completed':
        return '暂无已完成的订单';
      case 'cancelled':
        return '暂无已取消的订单';
      default:
        return '暂无订单';
    }
  }

  Widget _buildOrderItem(OrderItem order) {
    final Color primaryColor = Theme.of(context).colorScheme.primary;
    return Container(
      margin: const EdgeInsets.only(bottom: 15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => OrderDetailPage(order: order),
            ),
          );
        },
        child: Column(
          children: [
            // 订单头部
            Container(
              padding: const EdgeInsets.all(15),
              decoration: const BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    color: Color(0xFFEEEEEE),
                    width: 0.5,
                  ),
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    order.getStatusIcon(),
                    size: 20,
                    color: order.getStatusColor(),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    order.getStatusText(),
                    style: TextStyle(
                      color: order.getStatusColor(),
                      fontSize: 14,
                    ),
                  ),
                  const Spacer(),
                  Text(
                    order.time,
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
            // 订单内容
            Padding(
              padding: const EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: primaryColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Icon(
                          Icons.local_shipping,
                          color: primaryColor,
                          size: 24,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              order.title,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              order.description,
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 15),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '订单金额',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                      Text(
                        '¥${order.amount}',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // 订单底部按钮
            if (order.actions.isNotEmpty)
              Container(
                padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
                decoration: const BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: Color(0xFFEEEEEE),
                      width: 0.5,
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: order.actions.map((action) {
                    bool isPrimary = action == '立即支付' || action == '确认完成';
                    return Padding(
                      padding: const EdgeInsets.only(left: 12),
                      child: OutlinedButton(
                        onPressed: () {
                          // 处理按钮点击
                        },
                        style: OutlinedButton.styleFrom(
                          foregroundColor: isPrimary ? Colors.white : Colors.grey[600],
                          backgroundColor: isPrimary ? primaryColor : Colors.white,
                          side: BorderSide(
                            color: isPrimary ? primaryColor : Colors.grey[300]!,
                          ),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 8,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: Text(
                          action,
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: isPrimary ? FontWeight.w600 : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
          ],
        ),
      ),
    );
  }

  List<OrderItem> _getOrders(String type) {
    // 生成多条订单数据
    List<OrderItem> orders = [];
    switch (type) {
      case 'pending_accept':
        for (int i = 0; i < 10; i++) {
          orders.add(OrderItem(
            title: '大件搬运服务 ${i + 1}',
            description: '北京市朝阳区 → 海淀区',
            time: '2024-01-${21 - i} 10:30',
            amount: 399 + i * 10,
            status: 'pending_accept',
            actions: ['取消订单', '修改订单'],
          ));
        }
        break;
      case 'serving':
        for (int i = 0; i < 10; i++) {
          orders.add(OrderItem(
            title: '大件搬运服务 ${i + 1}',
            description: '北京市朝阳区 → 海淀区',
            time: '2024-01-${20 - i} 14:30',
            amount: 299 + i * 10,
            status: 'serving',
            actions: ['取消订单'],
          ));
        }
        break;
      case 'pending':
        for (int i = 0; i < 10; i++) {
          orders.add(OrderItem(
            title: '家具拆装服务 ${i + 1}',
            description: '北京市西城区望京南路10号',
            time: '2024-01-${19 - i} 16:20',
            amount: 199 + i * 10,
            status: 'pending',
            actions: ['立即支付'],
          ));
        }
        break;
      case 'completed':
        for (int i = 0; i < 10; i++) {
          orders.add(OrderItem(
            title: '小件搬运服务 ${i + 1}',
            description: '北京市海淀区中关村',
            time: '2024-01-${18 - i} 09:30',
            amount: 149 + i * 10,
            status: 'completed',
            actions: ['再次下单'],
          ));
        }
        break;
      case 'cancelled':
        for (int i = 0; i < 10; i++) {
          orders.add(OrderItem(
            title: '小件搬运服务 ${i + 1}',
            description: '北京市东城区东直门',
            time: '2024-01-${17 - i} 11:20',
            amount: 99 + i * 10,
            status: 'cancelled',
            actions: ['重新下单'],
          ));
        }
        break;
    }
    return orders;
  }
}

class OrderItem {
  final String title;
  final String description;
  final String time;
  final double amount;
  final String status;
  final List<String> actions;

  OrderItem({
    required this.title,
    required this.description,
    required this.time,
    required this.amount,
    required this.status,
    required this.actions,
  });

  Color getStatusColor() {
    switch (status) {
      case 'pending_accept':
        return Colors.purple;
      case 'serving':
        return const Color(0xFFFF5722);
      case 'pending':
        return Colors.orange;
      case 'completed':
        return Colors.green;
      case 'cancelled':
        return Colors.grey;
      default:
        return Colors.grey;
    }
  }

  IconData getStatusIcon() {
    switch (status) {
      case 'pending_accept':
        return Icons.access_time;
      case 'serving':
        return Icons.directions_car;
      case 'pending':
        return Icons.payment;
      case 'completed':
        return Icons.check_circle;
      case 'cancelled':
        return Icons.cancel;
      default:
        return Icons.error;
    }
  }

  String getStatusText() {
    switch (status) {
      case 'pending_accept':
        return '待接单';
      case 'serving':
        return '服务中';
      case 'pending':
        return '待结算';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  }
} 